from typer import Typer
import typer
from sqlalchemy import create_engine, MetaData, select
from forward.config import get_settings
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from forward.utils.tools import ToolsUtil

Base = declarative_base()
settings = get_settings()

db = Typer(name="db", help="数据库初始化一些命令等")
# 获取数据库 URL
database_url = settings.database_url

# 创建数据库引擎
engine = create_engine(database_url)
Session = sessionmaker(bind=engine)
session = Session()


@db.command(help="初始化所有表")
def create_all_tables():

    # 创建所有表
    Base.metadata.create_all(engine)


@db.command(help="查询表")
def search_table(table_name: str):
    tables = Base.metadata.tables
    for table in tables:
        print("code table", table)
        if table == table_name:
            return table


@db.command(name="code-tables")
def get_all_code_tables():
    tables = Base.metadata.tables
    # Base._decl_class_registry
    for table in tables:
        typer.echo(table)
    # return Base._decl_class_registry.values()


@db.command(name="db-tables")
def get_all_db_tables():
    # 创建 MetaData 对象并反射数据库结构
    metadata = MetaData()
    metadata.reflect(bind=engine)

    # 获取所有表的名称
    table_names = metadata.tables.keys()

    # 打印所有表的名称
    for table_name in table_names:
        typer.echo(table_name)
    return table_names


@db.command()
def create_admin(username: str = "admin", password: str = "123456"):
    from forward.model.tables.system import SystemAuthAdminModel
    from forward.dependencies.database import db

    password = ToolsUtil.make_md5(password + "5Xar0")
    statement = select(SystemAuthAdminModel).where(
        SystemAuthAdminModel.username == username
    )
    one: SystemAuthAdminModel = session.execute(statement).scalar()

    if not one:
        one = SystemAuthAdminModel(username=username)

    setattr(one, "password", password)
    session.add(one)
    session.commit()
    typer.echo("创建成功")


@db.command(name="db", help="删除所有表")
def mian():
    typer.echo("db is run")


@db.command(name="test-mysql-connect", help="测试数据库连接是否正常")
def test_mysql_content():
    try:
        engine.connect()
        typer.echo("数据库连接正常")
    except Exception as e:
        typer.echo(f"数据库连接异常: {e}")
